use async_trait::async_trait;
use fluviox_shared::{Result, models::DataRecord};
use serde_json::Value;
use std::collections::HashMap;

/// 连接器配置trait
pub trait ConnectorConfig: Send + Sync {
    /// 验证配置是否有效
    fn validate(&self) -> Result<()>;
    
    /// 获取配置的JSON表示
    fn to_json(&self) -> Result<Value>;
    
    /// 从JSON创建配置
    fn from_json(value: Value) -> Result<Self> where Self: Sized;
}

/// 数据源连接器trait
#[async_trait]
pub trait SourceConnector: Send + Sync {
    type Config: ConnectorConfig;
    
    /// 连接器名称
    fn name(&self) -> &str;
    
    /// 连接器版本
    fn version(&self) -> &str;
    
    /// 连接器描述
    fn description(&self) -> &str;
    
    /// 初始化连接器
    async fn initialize(&mut self, config: Self::Config) -> Result<()>;
    
    /// 测试连接
    async fn test_connection(&self) -> Result<bool>;
    
    /// 开始数据提取
    async fn start(&mut self) -> Result<()>;
    
    /// 停止数据提取
    async fn stop(&mut self) -> Result<()>;
    
    /// 读取数据记录
    async fn read_records(&mut self, batch_size: usize) -> Result<Vec<DataRecord>>;
    
    /// 获取连接器状态
    fn status(&self) -> ConnectorStatus;
    
    /// 获取连接器指标
    fn metrics(&self) -> ConnectorMetrics;
}

/// 目标连接器trait
#[async_trait]
pub trait DestinationConnector: Send + Sync {
    type Config: ConnectorConfig;
    
    /// 连接器名称
    fn name(&self) -> &str;
    
    /// 连接器版本
    fn version(&self) -> &str;
    
    /// 连接器描述
    fn description(&self) -> &str;
    
    /// 初始化连接器
    async fn initialize(&mut self, config: Self::Config) -> Result<()>;
    
    /// 测试连接
    async fn test_connection(&self) -> Result<bool>;
    
    /// 开始数据写入
    async fn start(&mut self) -> Result<()>;
    
    /// 停止数据写入
    async fn stop(&mut self) -> Result<()>;
    
    /// 写入数据记录
    async fn write_records(&mut self, records: Vec<DataRecord>) -> Result<usize>;
    
    /// 获取连接器状态
    fn status(&self) -> ConnectorStatus;
    
    /// 获取连接器指标
    fn metrics(&self) -> ConnectorMetrics;
}

/// 连接器状态
#[derive(Debug, Clone, PartialEq)]
pub enum ConnectorStatus {
    /// 未初始化
    Uninitialized,
    /// 已初始化
    Initialized,
    /// 运行中
    Running,
    /// 已停止
    Stopped,
    /// 错误状态
    Error(String),
}

/// 连接器指标
#[derive(Debug, Clone)]
pub struct ConnectorMetrics {
    /// 处理的记录数
    pub records_processed: u64,
    /// 处理的字节数
    pub bytes_processed: u64,
    /// 错误数
    pub errors_count: u64,
    /// 最后活动时间
    pub last_activity: Option<chrono::DateTime<chrono::Utc>>,
    /// 平均处理延迟（毫秒）
    pub avg_latency_ms: f64,
    /// 吞吐量（记录/秒）
    pub throughput_rps: f64,
}

impl Default for ConnectorMetrics {
    fn default() -> Self {
        Self {
            records_processed: 0,
            bytes_processed: 0,
            errors_count: 0,
            last_activity: None,
            avg_latency_ms: 0.0,
            throughput_rps: 0.0,
        }
    }
}

/// 连接器元数据
#[derive(Debug, Clone)]
pub struct ConnectorMetadata {
    pub name: String,
    pub version: String,
    pub description: String,
    pub connector_type: ConnectorType,
    pub supported_sync_modes: Vec<SyncMode>,
    pub configuration_schema: Value,
}

/// 连接器类型
#[derive(Debug, Clone, PartialEq)]
pub enum ConnectorType {
    Source,
    Destination,
}

/// 同步模式
#[derive(Debug, Clone, PartialEq)]
pub enum SyncMode {
    FullRefresh,
    Incremental,
    RealTime,
}

/// 连接器工厂trait
pub trait ConnectorFactory: Send + Sync {
    /// 创建数据源连接器
    fn create_source(&self, connector_type: &str) -> Result<Box<dyn std::any::Any + Send + Sync>>;

    /// 创建目标连接器
    fn create_destination(&self, connector_type: &str) -> Result<Box<dyn std::any::Any + Send + Sync>>;

    /// 获取支持的数据源连接器列表
    fn supported_sources(&self) -> Vec<ConnectorMetadata>;

    /// 获取支持的目标连接器列表
    fn supported_destinations(&self) -> Vec<ConnectorMetadata>;
}
